package com.achievo.know.job;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.achievo.know.component.impl.FileManagerConfig;
import com.achievo.know.domain.FileAttachmentRepository;

public class DelTempFileDailyJob {
	
	@Autowired
	private FileManagerConfig config;
	@Autowired
	private FileAttachmentRepository attsReps;

	public FileManagerConfig getConfig() {
		return config;
	}

	public void setConfig(FileManagerConfig config) {
		this.config = config;
	}

	public FileAttachmentRepository getAttsReps() {
		return attsReps;
	}

	public void setAttsReps(FileAttachmentRepository attsReps) {
		this.attsReps = attsReps;
	}

	public void work() {
		try {
			System.out.println("任务调度:清除临时文件及记录");
			//delete zip temp files
			File zip=config.getZipFileStoreDirectory();
			File[] zips=zip.listFiles();
			for(File z:zips){
				FileUtils.forceDelete(z);
			}
			
			//delete upload temp files
			File up=config.getUploadFileStoreDirectory();
			File[] ups=up.listFiles();
			for(File u:ups){
				if(u.isDirectory()){
					FileUtils.deleteDirectory(u);
				}
				if(u.isFile()){
					FileUtils.forceDelete(u);
				}
			}
			
			//delete persist removed files
			File ps=config.getPersistFileStoreDirectory();
			File[] pss=ps.listFiles();
			for(File p:pss){
				if(p.isDirectory()){
					File[] subPs=p.listFiles();
					for(File sp:subPs){
						boolean isExs=attsReps.exists(FilenameUtils.getBaseName(sp.getName()));
						if(!isExs)
							FileUtils.forceDelete(sp);
					}
				}
				if(p.isFile()){
					boolean isExs=attsReps.exists(FilenameUtils.getBaseName(p.getName()));
					if(!isExs)
						FileUtils.forceDelete(p);
				}
			}
			
			//delete image removed files
			File ns=config.getImageStoreDirectory();
			File[] nss=ns.listFiles();
			for(File p:nss){
				if(p.isDirectory()){
					File[] subPs=p.listFiles();
					for(File sp:subPs){
						boolean isExs=attsReps.exists(FilenameUtils.getBaseName(sp.getName()));
						boolean isExsP=attsReps.existsPhoto(sp.getName());
						if(!isExs && !isExsP)
							FileUtils.forceDelete(sp);
					}
				}
				if(p.isFile()){
					boolean isExs=attsReps.exists(FilenameUtils.getBaseName(p.getName()));
					boolean isExsP=attsReps.existsPhoto(p.getName());
					if(!isExs && !isExsP)
						FileUtils.forceDelete(p);
				}
			}
			
			//delete swf removed files
			File swfs=config.getSwfFileStoreDirectory();
			File[] swfss=swfs.listFiles();
			for(File p:swfss){
				if(p.isDirectory()){
					boolean isExs=attsReps.exists(FilenameUtils.getBaseName(p.getName()));
					if(!isExs)
						FileUtils.deleteDirectory(p);
				}
			}
			
			//delete temp attachment records
			attsReps.deleteTempAttachments();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
